package org.fire.activity;

import org.fire.FireApplication;
import org.fire.R;
import org.fire.exception.MinaConnectionException;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;

public class SplashActivity extends BaseActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_splash);

		new ConnectServerTask().execute();
	}

	private class ConnectServerTask extends AsyncTask<Void, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				Thread.sleep(1500);
			} catch (InterruptedException e) {
			}

			publishProgress(0);
			try {
				FireApplication.getApplication(SplashActivity.this)
						.connectToServer();
			} catch (MinaConnectionException e1) {
				publishProgress(2);
				return false;
			}

			try {
				Thread.sleep(1500);
			} catch (InterruptedException e) {
			}

			publishProgress(1);

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}

			return true;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			int value = values[0];
			TextView textView = (TextView) SplashActivity.this
					.findViewById(R.id.splashWaiting);
			if (0 == value) {
				textView.setText(R.string.splashWaitingText_connect);

			} else if (1 == value) {
				textView.setText(R.string.splashWaitingText_connect_success);

			} else if (2 == value) {
				textView.setText(R.string.splashWaitingText_connect_failed);
				ProgressBar proBar = (ProgressBar) SplashActivity.this
						.findViewById(R.id.splashProgressBar);
				proBar.setVisibility(View.INVISIBLE);
			}
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				Intent intent = new Intent(SplashActivity.this,
						MainActivity.class);
				SplashActivity.this.startActivity(intent);
			}
		}

	}

}
